package com.hry.store.service.impl;

import com.hry.store.dao.UserMapper;
import com.hry.store.pojo.User;
import com.hry.store.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * 邮件发送
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${domain.name}")
    private String domainName;
    @Value("${mail.title}")
    private String title;


    /**
     * 发送邮件
     * @param url
     * @param userEmail
     */
    @Override
    public void sendMail(String url, String userEmail) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(userEmail);
        mailMessage.setText(url);
        // 抄送
        mailMessage.setBcc("shmilywsx1234@163.com");
        mailMessage.setSubject(title);
        javaMailSender.send(mailMessage);
    }


    public void registerNotify(String userEmail, String key) {
        String url = "http://" + domainName + "/user/activate?email=" + userEmail + "&key=" + key;
        sendMail(url, userEmail);
    }

    @Override
    public boolean enable(String email, String key) {
        if (!StringUtils.isBlank(key)) {
            User updateUser = new User();
            // 设置为可用
            updateUser.setStatus(1);
            updateUser.setUserEmail(email);
            updateUser.setVerifyCode("用户已经被激活");
            userMapper.updateUserStatus(updateUser);
            return true;
        }
        return false;
    }
}
